package core

import (
	"fmt"
	"net/http"
)

type ServerHandler struct {
	http.Handler
}

func (this *ServerHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
	session := NewSession(resp, req)
	//defer session.Timer.Done()

	defer func() {
		session.Timer.Done()
		//添加一些公共的后续操作
		tFinisher := session.Timer.Add("GlobalFinisher")
		for name, action := range routeHub.Finisher {
			tFinisherItem := session.Timer.Add(name)
			(*action)(session)
			tFinisherItem.Done()
			if session.IsStop {
				return
			}
		}
		tFinisher.Done()
	}()

	//添加一些公共的前置操作
	tPrepare := session.Timer.Add("GlobalPreparer")
	for name, action := range routeHub.Preparer {
		tPrepareItem := session.Timer.Add(name)
		(*action)(session)
		tPrepareItem.Done()
		if session.IsStop {
			return
		}
	}
	tPrepare.Done()

	//业务逻辑处理流程
	Dispatch(session)

}

func NewServerHandler() *ServerHandler {
	hd := new(ServerHandler)
	return hd
}

func GetServerHttpUrl() string {
	return fmt.Sprintf("http://%s:%d", ConfigServer.ServerHost, ConfigServer.ServerPort)
}
